package com.collins.thread.practices.redPocket;

import java.math.BigDecimal;
import java.math.RoundingMode;

public class Receiver implements Runnable {
    @Override
    public void run() {
        synchronized (Sender.lock) {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            if (Sender.people == 1) {
                System.out.println(Thread.currentThread().getName() + " gets " + Sender.money + " RMB");
            } else {
                // bound = (people-1) * MINIMUM_MONEY
                BigDecimal bound = Sender.money.subtract(BigDecimal.valueOf((Sender.people - 1) *
                        Sender.MINIMUM_MONEY.doubleValue())).setScale(2, RoundingMode.HALF_UP);
                // TODO tweaks on amount of pocket money
                BigDecimal upper = BigDecimal.valueOf(bound.doubleValue() * 0.95)
                        .setScale(2, RoundingMode.HALF_UP);
                BigDecimal lower = BigDecimal.valueOf(bound.doubleValue() * 0.05)
                        .setScale(2, RoundingMode.HALF_UP);
                BigDecimal quota = new BigDecimal("0.01");
                BigDecimal unit = BigDecimal.valueOf(Sender.rand.nextInt(20))
                        .multiply(Sender.ttl_money).setScale(2, RoundingMode.HALF_UP);
                // determine add or subtract
                int flag = Sender.rand.nextInt(2);
                BigDecimal pocket;
                if (flag == 0) {
                    pocket = Sender.TTL_AVERAGE_MONEY.subtract(quota.multiply(unit))
                            .setScale(2, RoundingMode.HALF_UP);
                } else {
                    pocket = Sender.TTL_AVERAGE_MONEY.add(quota.multiply(unit))
                            .setScale(2, RoundingMode.HALF_UP);
                }
                // make sure too much or too little
                if (pocket.compareTo(upper) > 0) {
                    pocket = upper;
                }
                if (pocket.compareTo(lower) < 0) {
                    pocket = lower;
                }
                // int pocket = Sender.rand.nextInt(bound);
                if (pocket.doubleValue() < Sender.MINIMUM_MONEY.doubleValue()) {
                    pocket = Sender.MINIMUM_MONEY;
                }
                System.out.println(Thread.currentThread().getName() + " gets " + pocket + " RMB");
                Sender.money = Sender.money.subtract(pocket).setScale(2, RoundingMode.HALF_UP);
                Sender.people--;
            }
        }
    }
}
